home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / lib2to3 / pgen2 / literals.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-04-20  |  2.0 KB  |  85 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Safely evaluate Python string literals without using eval().'''
  5. import re
  6. simple_escapes = {
  7.     'a': '\x07',
  8.     'b': '\x08',
  9.     'f': '\x0c',
  10.     'n': '\n',
  11.     'r': '\r',
  12.     't': '\t',
  13.     'v': '\x0b',
  14.     "'": "'",
  15.     '"': '"',
  16.     '\\': '\\' }
  17.  
  18. def escape(m):
  19.     (all, tail) = m.group(0, 1)
  20.     if not all.startswith('\\'):
  21.         raise AssertionError
  22.     esc = simple_escapes.get(tail)
  23.     if esc is not None:
  24.         return esc
  25.     if tail.startswith('x'):
  26.         hexes = tail[1:]
  27.         if len(hexes) < 2:
  28.             raise ValueError("invalid hex string escape ('\\%s')" % tail)
  29.         len(hexes) < 2
  30.         
  31.         try:
  32.             i = int(hexes, 16)
  33.         except ValueError:
  34.             esc is not None
  35.             esc is not None
  36.             all.startswith('\\')
  37.             raise ValueError("invalid hex string escape ('\\%s')" % tail)
  38.         except:
  39.             esc is not None<EXCEPTION MATCH>ValueError
  40.         
  41.  
  42.     esc is not None
  43.     
  44.     try:
  45.         i = int(tail, 8)
  46.     except ValueError:
  47.         esc is not None
  48.         esc is not None
  49.         all.startswith('\\')
  50.         raise ValueError("invalid octal string escape ('\\%s')" % tail)
  51.     except:
  52.         esc is not None
  53.  
  54.     return chr(i)
  55.  
  56.  
  57. def evalString(s):
  58.     if not s.startswith("'") and s.startswith('"'):
  59.         raise AssertionError, repr(s[:1])
  60.     q = s[0]
  61.     if s[:3] == q * 3:
  62.         q = q * 3
  63.     
  64.     if not s.endswith(q):
  65.         raise AssertionError, repr(s[-len(q):])
  66.     if not len(s) >= 2 * len(q):
  67.         raise AssertionError
  68.     s = s[len(q):-len(q)]
  69.     return re.sub('\\\\(\\\'|\\"|\\\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})', escape, s)
  70.  
  71.  
  72. def test():
  73.     for i in range(256):
  74.         c = chr(i)
  75.         s = repr(c)
  76.         e = evalString(s)
  77.         if e != c:
  78.             print i, c, s, e
  79.             continue
  80.     
  81.  
  82. if __name__ == '__main__':
  83.     test()
  84.  
  85.